<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
			<!--商品信息-->
			<view class="detail-item">
				<uni-section title="商品信息" type="line"></uni-section>
				<view class="detail-content formRef">
					<uni-forms ref="formRef" :model="formData" :rules="formRules" labelWidth="80px">
					  <uni-forms-item label="区域" name="regionCode">
					    <uni-data-select
					    	v-model="formData.regionCode"
					    	placeholder="请选择区域"
					    	:localdata="setStore.allProvinceList"></uni-data-select>
					  </uni-forms-item>
						<uni-forms-item label="商品名称" name="name" required>
					    <uni-easyinput disabled v-model="formData.name" placeholder="请输入商品名称" />
					  </uni-forms-item>
					  <uni-forms-item label="商品编码" name="code">
					    <uni-easyinput disabled v-model="formData.code" placeholder="请输入商品编码" />
					  </uni-forms-item>
					  <uni-forms-item label="商品条码" name="barcode">
					    <uni-easyinput v-model="formData.barcode" placeholder="请输入商品条码" />
					  </uni-forms-item>
						<uni-forms-item label="采购商品" name="purchaseFlag">
							<view class="search-form-checkbox main-flex">
								<uni-data-checkbox v-model="formData.purchaseFlag" :localdata="[
									{ value: 0, text: '否'},
									{ value: 1, text: '是'}
								]" />
							</view>
						</uni-forms-item>
					  <uni-forms-item label="商品卖点" name="marketTitle">
					    <uni-easyinput type="textarea" v-model="formData.marketTitle" placeholder="请输入商品卖点" />
					  </uni-forms-item>
					  <uni-forms-item label="关键词" name="keyword">
					    <uni-easyinput v-model="formData.keyword" placeholder="请输入关键词" />
					  </uni-forms-item>
						
						<uni-forms-item label="商品主图" name="image">
							<up-upload
								:fileList="fileList.image"
								@afterRead="afterRead"
								@delete="deletePic"
								name="image"
								:maxCount="1"
								></up-upload>
						  <uni-easyinput style="display: none;" v-model="formData.image" placeholder="上传商品主图" />
						</uni-forms-item>
						<uni-forms-item label="banner图" name="banner">
							<up-upload
								:fileList="fileList.banner"
								@afterRead="afterRead"
								@delete="deletePic"
								name="banner"
								multiple
								:maxCount="5"
								></up-upload>
						  <uni-easyinput style="display: none;" v-model="formData.banner" placeholder="上传banner图" />
						</uni-forms-item>
					  <!-- <uni-forms-item label="商品视频" name="video">
							<up-upload
								:fileList="fileList.video"
								@afterRead="afterRead"
								@delete="deletePic"
								name="video"
								accept="video"
								:maxCount="1"
								></up-upload>
					    <uni-easyinput style="display: none;" v-model="formData.video" placeholder="上传商品视频" />
					  </uni-forms-item>
					  <uni-forms-item label="视频封面" name="videoCoverImage">
							<up-upload
								:fileList="fileList.videoCoverImage"
								@afterRead="afterRead"
								@delete="deletePic"
								name="videoCoverImage"
								:maxCount="1"
								></up-upload>
					    <uni-easyinput style="display: none;" v-model="formData.videoCoverImage" placeholder="上传视频封面" />
					  </uni-forms-item>
					  <uni-forms-item label="商品归类" name="productClassify">
					    <uni-data-select
					    	v-model="formData.productClassify"
					    	placeholder="请选择商品归类"
					    	:localdata="productClassifyList"></uni-data-select>
					  </uni-forms-item> -->
						<uni-forms-item label="类型名称" name="typeId" required>
						  <uni-data-select
						  	v-model="formData.typeId"
						  	placeholder="请选择类型名称"
								@change="changeTypeId"
						  	:localdata="productTypeList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="商品单位" name="unit" required>
						  <uni-data-select
						  	v-model="formData.unit"
						  	placeholder="请选择商品单位"
						  	:localdata="zyzProductUnitList"></uni-data-select>
						</uni-forms-item>
					  <uni-forms-item label="显示顺序" name="sortKey">
					    <uni-easyinput type="number" v-model="formData.sortKey" placeholder="请输入显示顺序" />
					  </uni-forms-item>
					  <uni-forms-item label="销量" name="salesNumber" required>
					    <uni-easyinput type="number" v-model="formData.salesNumber" placeholder="请输入销量" />
					  </uni-forms-item>
					  <uni-forms-item label="库存" name="stock" required>
					    <uni-easyinput type="number" v-model="formData.stock" placeholder="请输入库存" />
					  </uni-forms-item>
					  <uni-forms-item label="重量(Kg)" name="productWeight">
					    <uni-easyinput type="number" v-model="formData.productWeight" placeholder="请输入重量(Kg)" />
					  </uni-forms-item>
					  <uni-forms-item label="采购价" name="purchasePrice" v-show="checkPermi(['zhouyz:purchaseOrder:price'])">
					    <uni-easyinput @input="changePurchasePrice" type="number" v-model="formData.purchasePrice" placeholder="请输入采购价" />
					  </uni-forms-item>
					  <uni-forms-item label="最低售价" name="sellPrice" v-show="checkPermi(['zhouyz:productInfo:price'])">
					    <uni-easyinput type="number" v-model="formData.sellPrice" placeholder="请输入最低售价" />
					  </uni-forms-item>
					  <uni-forms-item label="市场价" name="marketPrice" v-show="checkPermi(['zhouyz:productInfo:price'])">
					    <uni-easyinput type="number" v-model="formData.marketPrice" placeholder="请输入市场价" />
					  </uni-forms-item>
						<uni-forms-item label="渠道设置" class="vertical" v-show="checkPermi(['zhouyz:productPrice:list'])">
						  <view class="price">
						  	<view class="price-item" :class="parseFloat(item.sellPrice) < parseFloat(formData.sellPrice) ? 'price-tip' : ''" v-for="item in priceList">
									<view class="price-item-top main-flex">
										<view class="price-item-td">
											<uni-tag size="small" type="primary" :class="`sellChannel${item.sellChannel}`" :text="arrText(sellChannelList, item.sellChannel)" />
										</view>
										<view class="price-item-td main-flex-item main-flex">
											销售价：<uni-easyinput type="number" v-model="item.sellPrice" placeholder="销售价" />
										</view>
										<view class="price-item-td main-flex-item main-flex">
											起订数量：<uni-easyinput type="number" v-model="item.minimum" placeholder="起订数量" />
										</view>
									</view>
									<view class="price-item-bottom main-flex">
										<view class="price-item-td">
											<up-switch
												:activeValue="1"
												:inactiveValue="0"
												v-model="item.opened"
												:activeColor="bgColor(item.sellChannel)"
												size="18" >
											</up-switch>
										</view>
										<view class="price-item-td main-flex-item main-flex">
											货运成本：<uni-easyinput type="number" v-model="item.logisticsCost" placeholder="货运成本" />
										</view>
										<view class="price-item-td main-flex-item main-flex">
											备注：<uni-easyinput v-model="item.remark" placeholder="备注" />
										</view>
									</view>
								</view>
						  </view>
						</uni-forms-item>
						<uni-forms-item label="规格商品" class="vertical">
							<view class="vertical-add main-flex">
								<up-button
									class="operate-btn main-flex"
									size="mini"
									type="primary"
									@click="addFun(1)">
									<uni-icons class="operate-btn-icon" type="plusempty" size="28rpx" color="#ffffff"></uni-icons>
									<view class="operate-btn-text">新增</view>
								</up-button>
							</view>
							<view class="table">
								<ty-table
									:data="specsList"
									:columns="productListColumns"
									:sortable="true"
									:cellClassName="() => 'table-cell'"
									:headerCellClassName="() => 'table-cell'"
									stripe
									border>
									<template v-slot:status="{ row }">
										<uni-tag :type="row.status === 1 ? 'success' : 'error'" size="small" :text="row.status === 1 ? '上架' : '下架'" />
									</template>
									<template v-slot:delete="{ row }">
										<up-button
											class="operate-btn main-flex"
											size="mini"
											type="error"
											@click="delFun(row, 1)">
											<view class="operate-btn-text">删除</view>
										</up-button>
									</template>
								</ty-table>
							</view>
						</uni-forms-item>
						<uni-forms-item label="关联商品" class="vertical">
							<view class="vertical-add main-flex">
								<up-button
									class="operate-btn main-flex"
									size="mini"
									type="primary"
									@click="addFun(2)">
									<uni-icons class="operate-btn-icon" type="plusempty" size="28rpx" color="#ffffff"></uni-icons>
									<view class="operate-btn-text">新增</view>
								</up-button>
							</view>
							<view class="table">
								<ty-table
									:data="relationList"
									:columns="productListColumns"
									:sortable="true"
									:cellClassName="() => 'table-cell'"
									:headerCellClassName="() => 'table-cell'"
									stripe
									border>
									<template v-slot:status="{ row }">
										<uni-tag :type="row.status === 1 ? 'success' : 'error'" size="small" :text="row.status === 1 ? '上架' : '下架'" />
									</template>
									<template v-slot:delete="{ row }">
										<up-button
											class="operate-btn main-flex"
											size="mini"
											type="error"
											@click="delFun(row, 2)">
											<view class="operate-btn-text">删除</view>
										</up-button>
									</template>
								</ty-table>
							</view>
						</uni-forms-item>
					  <uni-forms-item label="备注" name="remark">
					    <uni-easyinput type="textarea" v-model="formData.remark" placeholder="请输入备注" />
					  </uni-forms-item>
					  <uni-forms-item label="送积分" name="sendIntegralFlag">
							<view class="search-form-checkbox main-flex">
								<up-switch
									:activeValue="1"
									:inactiveValue="0"
									activeColor="#13ce66"
									inactiveColor="#ff4949"
									v-model="formData.sendIntegralFlag"
									size="20" >
								</up-switch>
							</view>
					  </uni-forms-item>
						<uni-forms-item label="单件送" name="sendIntegralValue" v-if="formData.sendIntegralFlag === 1">
						  <uni-easyinput type="number" v-model="formData.sendIntegralValue" placeholder="请输入单件送" />
						</uni-forms-item>
						<uni-forms-item label="最多送" name="mastSendIntegral" v-if="formData.sendIntegralFlag === 1">
						  <uni-easyinput type="number" v-model="formData.mastSendIntegral" placeholder="请输入最多送" />
						</uni-forms-item>
					</uni-forms>
					<button type="primary" :disabled="isSubmit" :loading="isSubmit" @click="submit">提交</button>
				</view>
			</view>
		</view>
		
		<!--商品选择-->
		<ty-product-picker 
			:showProduct="showProduct"
			@change="changeProduct"
			@close="closeProduct">
		</ty-product-picker>
		
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import { timeFormat } from 'uview-plus'
import { productEdit, productDetail, productType } from "@/api/erp_api/product"
import { zyzProductUnit } from "@/api/system/dict/data"
import { allProvince } from "@/api/erp_api/region"
import { upload } from "@/api/system/common"
import { getUserLocation, arrText } from '@/utils/ty.js';
import { productClassifyList, sellChannelList } from '@/utils/config.js'
import { supplierProduct } from "@/api/erp_api/purchase"
import { nextTick } from 'process';

	const userStore = useUserStore()
	const setStore = useSetStore()
	const id = ref('')
	onLoad(async (option) => {
		await getProductType()
		await getZyzProductUnit()
		if (option.id) {
			uni.setNavigationBarTitle({
				title: '修改商品'
			})
			id.value = option.id
			getDetail()
		}
	})
	
	// 获取商品类别
	const productTypeList = ref([])
	const getProductType = () => {
		return productType().then(res => {
			productTypeList.value = res.rows.map(item => {
				return {
					...item,
					value: item.id,
					text: `${item.parentName}->${item.name}`
				}
			}).filter(item => item.parentId) || []
		})
	}
	
	// 商品单位
	const zyzProductUnitList = ref([])
	const getZyzProductUnit = () => {
		return zyzProductUnit().then(res => {
			zyzProductUnitList.value = res.data.map(item => {
				return {
					...item,
					value: item.dictLabel,
					text: item.dictLabel
				}
			}) || []
		})
	}
	
	// 获取详情
	const info = ref({})
	const priceList = ref([])
	const isLoading = ref(false)
	const getDetail = () => {
		const params = {
			id: id.value
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		productDetail(params).then(res => {
			info.value = res.data || {}
			formData.value = {
				regionCode: res.data.regionCode,
				name: res.data.name,
				code: res.data.code,
				barcode: res.data.barcode,
				purchaseFlag: res.data.purchaseFlag,
				marketTitle: res.data.marketTitle,
				keyword: res.data.keyword,
				video: res.data.video,
				videoCoverImage: res.data.videoCoverImage,
				image: res.data.image,
				banner: res.data.banner,
				typeId: res.data.typeId,
				unit: res.data.unit,
				productClassify: res.data.productClassify,
				sortKey: res.data.sortKey,
				salesNumber: res.data.salesNumber,
				stock: res.data.stock,
				productWeight: res.data.productWeight,
				purchasePrice: res.data.purchasePrice,
				sellPrice: res.data.sellPrice,
				marketPrice: res.data.marketPrice,
				remark: res.data.remark,
				sendIntegralFlag: res.data.sendIntegralFlag,
				sendIntegralValue: res.data.sendIntegralValue,
				mastSendIntegral: res.data.mastSendIntegral
			}
			priceList.value = res.data.priceList ? res.data.priceList : []
			fileList.value = {
				video: imgUrlList(res.data, 'video'),
				videoCoverImage: imgUrlList(res.data, 'videoCoverImage'),
				image: imgUrlList(res.data, 'image'),
				banner: imgUrlList(res.data, 'banner')
			}
			getSpecsList(res?.data?.specsList)
			getRelationList(res?.data?.relationList)
			isLoading.value = false
			uni.hideLoading()
	  }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// 图片显示
	const imgUrlList = (data, key) => {
		return data[key] ? data[key].split(',').map(item => {
			return {
				status: 'success',
				message: '上传成功',
				url: item,
				type: 'image'
			}
		}) : []
	}
	
	// 图片上传
	const fileList = ref({
		video: [],
		videoCoverImage: [],
		image: [],
		banner: []
	})
	
	// 删除图片
	const deletePic = (event) => {
	  fileList.value[`${event.name}`].splice(event.index, 1)
		formData.value[`${event.name}`] = fileList.value[`${event.name}`].map(item => item.url).join(',')
	}
	
	// 新增图片
	const afterRead = async (event) => {
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file)
	  let fileListLen = fileList.value[`${event.name}`].length
	  lists.map((item) => {
	    fileList.value[`${event.name}`].push({
	      ...item,
	      status: 'uploading',
	      message: '上传中',
	    });
	  });
	  for (let i = 0; i < lists.length; i++) {
	    const result = await upload(lists[i].url)
			const data = JSON.parse(result.data)
	    let item = fileList.value[`${event.name}`][fileListLen]
	    fileList.value[`${event.name}`].splice(fileListLen, 1, {
	      ...item,
	      status: 'success',
	      message: '',
	      url: data.url,
	    });
	    fileListLen++;
	  }
		formData.value[`${event.name}`] = fileList.value[`${event.name}`].map(item => item.url).join(',')
	};
	
	// 颜色
	const bgColor = (sellChannel) => {
		switch (sellChannel) {
			case 1 : 
				return '#2E86C1'
				break;
			case 2 :
				return '#28B463'
				break;
			case 3 :
				return '#E67E22'
				break;
			case 4 :
				return '#E74C3C'
				break;
		}
	}
	
	const getGrossProfit = (row) => {
		let grossProfit = 0.15
		if (row.productClassify === 1) {
			const typeFilter = productTypeList.value.filter(item => item.id == row.typeId)
			grossProfit = typeFilter?.[0]?.grossProfit || 0.15
		} else {
			grossProfit = 0.09
		}
		return 1 - grossProfit
	}
	// 采购价变动
	const changePurchasePrice = (e) => {
		getSellPrice()
	}
	// 选择类型
	const changeTypeId = (e) => {
		getSellPrice()
	}
	const getSellPrice = () => {
		nextTick(() => {
			if (formData.value.typeId && formData.value.purchasePrice) {
				const sellPrice = (parseFloat(formData.value.purchasePrice) / getGrossProfit(formData.value)).toFixed(2)
				formData.value.sellPrice = sellPrice
			}
		})
	}
	
	const specsList = ref([])
	const productListColumns = ref([
		{ title: '商品名称', key: 'name' },
		{ title: '单位', key: 'unit', width: '160rpx', align: 'center' },
		{ title: '状态', key: 'status', width: '100rpx', align: 'center' },
		{ title: '操作', key: 'delete', width: '100rpx', align: 'center' }
	])
	const getSpecsList = async (ids) => {
		if (ids) {
			const idsArr = ids.split(',')
			for(let i = 0; i < idsArr.length; i++) {
				const product = await productDetail({id: idsArr[i]})
				if (product.code === 200) {
					specsList.value.push({...product.data})
				} else {
					specsList.value.push({
						name: '商品信息错误',
						status: 0,
						unit: ''
					})
				}
			}
		}
	}
	const relationList = ref([])
	const getRelationList = async (ids) => {
		if (ids) {
			const idsArr = ids.split(',')
			for(let i = 0; i < idsArr.length; i++) {
				const product = await productDetail({id: idsArr[i]})
				if (product.code === 200) {
					relationList.value.push({...product.data})
				} else {
					relationList.value.push({
						name: '商品信息错误',
						status: 0,
						unit: ''
					})
				}
			}
		}
	}
	
	// 商品选择
	const showProduct = ref(false)
	const type = ref(0)
	const addFun = (e) => {
		showProduct.value = true
		type.value = e
	}
	const closeProduct = () => {
		showProduct.value = false
		type.value = 0
	}
	const changeProduct = (list) => {
		for(let i = 0; i < list.length; i++) {
			if (type.value === 1) { // 规格商品
				const filter = specsList.value.find(item => item.id === list[i].id)
				if (!filter) {
					specsList.value.push({
						...list[i]
					})
				}
			} else if (type.value === 2) { // 关联商品
				const filter = relationList.value.find(item => item.id === list[i].id)
				if (!filter) {
					relationList.value.push({
						...list[i]
					})
				}
			}
		}
	}
	// 删除商品
	const delFun = (row, type) => {
		if (type === 1) { // 规格商品
			specsList.value.splice(row.rowIndex, 1)
		} else if (type === 2) { // 关联商品
			relationList.value.splice(row.rowIndex, 1)
		}
	}
	
	// form表单数据
	const formData = ref({
		regionCode: '',
		name: '',
		code: '',
		barcode: '',
		purchaseFlag: 0,
		marketTitle: '',
		keyword: '',
		video: '',
		videoCoverImage: '',
		image: '',
		banner: '',
		typeId: '',
		unit: '',
		productClassify: '',
		sortKey: 0,
		salesNumber: '',
		stock: '',
		productWeight: '',
		purchasePrice: '',
		sellPrice: '',
		marketPrice: '',
		remark: '',
		sendIntegralFlag: 0,
		sendIntegralValue: '',
		mastSendIntegral: ''
	})
	const formRef = ref(null)
	const formRules = ref({
		name: {
			rules: [{ required: true, errorMessage: '请输入商品名称' }]
		},
		typeId: {
			rules: [{ required: true, errorMessage: '请选择类型名称' }]
		},
		unit: {
			rules: [{ required: true, errorMessage: '请选择商品单位' }]
		},
		salesNumber: {
			rules: [{ required: true, errorMessage: '请输入销量' }]
		},
		stock: {
			rules: [{ required: true, errorMessage: '请输入库存' }]
		}
	})
	const isSubmit = ref(false)
	// 提交
	const submit = () => {
		formRef.value.validate().then(formRes => {
			const params = { ...info.value, ...formRes }
			if (id.value) {
				params.id = id.value
			}
			if (params.typeId) {
				params.typeName = productTypeList.value.filter(item => item.id == params.typeId)[0]?.name
			}
			params.priceList = priceList.value
			// 批发
			const sellChannel1 = priceList.value.filter(item => item.sellChannel == 1)
			params.wholeOpened = sellChannel1[0]?.opened ? 1 : null
			params.wholePrice = sellChannel1[0]?.sellPrice || ''
			// 零售
			const sellChannel2 = priceList.value.filter(item => item.sellChannel == 2)
			params.retailOpened = sellChannel2[0]?.opened ? 1 : null
			params.retailPrice = sellChannel2[0]?.sellPrice || ''
			// 团购
			const sellChannel3 = priceList.value.filter(item => item.sellChannel == 3)
			params.groupOpened = sellChannel3[0]?.opened ? 1 : null
			params.groupPrice = sellChannel3[0]?.sellPrice || ''
			// 超市
			const sellChannel4 = priceList.value.filter(item => item.sellChannel == 4)
			params.shopOpened = sellChannel4[0]?.opened ? 1 : null
			params.shopPrice = sellChannel4[0]?.sellPrice || ''
			
			// 规格商品
			params.specsList = specsList.value.length > 0 ? specsList.value.map(item => item.id).join(',') : ''
			// 关联商品
			params.relationList = relationList.value.length > 0 ? relationList.value.map(item => item.id).join(',') : ''
			
			isSubmit.value = true
			productEdit(params).then(async (res) => {
				modal.showToast(res.msg)
				await uni.$u.sleep(1000)
				isSubmit.value = false
				if ((params.purchasePrice != info.value.purchasePrice
						|| params.regionCode != info.value.regionCode
						|| params.typeName != info.value.typeName
						|| params.unit != info.value.unit)
						&& checkPermi(['zhouyz:supplierProduct:list'])) {
					uni.showModal({
						content: `商品信息变动，是否前往修改供应商商品信息？`,
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: `/pages/purchase/supplierProduct?productId=${params.id}`
								})
							}
							if (res.cancel) {
								clear()
								uni.$emit('refreshList');  // 触发刷新事件
								uni.navigateBack({
									delta: 1
								})
							}
						}
					})
				} else {
					clear()
					uni.$emit('refreshList');  // 触发刷新事件
					uni.navigateBack({
						delta: 1
					})
				}
			}).catch((err) => {
				modal.showToast(err)
				isSubmit.value = false
			})
		})
	}
	// 清空
	const clear = () => {
		formData.value = {
			customerName: '',
			phone: '',
			regionCode: '',
			storeName: '',
			storeImag: '',
			addr: '',
			addrDetail: '',
			level: '',
			lng: '',
			lat: '',
			isPublic: ''
		}
	}
</script>

<style scoped lang="scss">
	.vertical {
		position: relative;
		flex-direction: column !important;
		&-add {
			position: absolute;
			top: -36px;
			right: 0;
			height: 36px;
		}
		.price {
			color: #333333;
			&-tip {
				background-color: #ff66cc;
			}
			&-item {
				padding: 5px 0;
				&-bottom {
					margin-top: 10px;
				}
				&-td {
					padding: 0 5px;
					font-size: 12px !important;
					:deep(.uni-easyinput__content-input) {
						height: 26px;
						font-size: 12px;
					}
					&-tag {
						background-color: #d1e9ff;
						border-color: #d1e9ff;
						color: #1890ff;
					}
				}
				&+.price-item {
					margin-top: 10px;
				}
			}
		}
	}
</style>
